package test;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class addFlightView extends JFrame {
    private JTextField flightIdField;
    private JButton addButton;

    public addFlightView() {
        setTitle("预定机票");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        JLabel flightIdLabel = new JLabel("选择航班的id");
        flightIdField = new JTextField();

        addButton = new JButton("添加");

        // 添加组件到窗口00
        add(flightIdLabel);
        add(flightIdField);

        add(new JLabel()); // 占位
        add(addButton);

        // 添加添加按钮的点击事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addUserInfoToDatabase();
            }
        });
    }

    private void addUserInfoToDatabase() {
        String flightId = flightIdField.getText();
        try {
            // 连接数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:Mysql://localhost:3306/airlines", "root", "123456");

            // 创建插入语句
            String insertQuery = "INSERT INTO air_order (user_id,flight_id, airway_id, passenger_name,passenger_id_card_num,contact,order_time) VALUES (?, ?, ?, ?,?, ?, ?, ?)";
            PreparedStatement statement = conn.prepareStatement(insertQuery);
            statement.setString(1, flightId);
            // 执行插入操作
            statement.executeUpdate();

            // 关闭连接和语句
            statement.close();
            conn.close();

            // 提示添加成功
            JOptionPane.showMessageDialog(this, "添加成功");

            // 清空输入框
            clearFields();

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "添加失败：" + e.getMessage());
        }
    }

    private void clearFields() {
        flightIdField.setText("");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            org.example.admin.flight.addFlightView userAddView = new org.example.admin.flight.addFlightView();
            userAddView.setSize(300, 200);
            userAddView.setVisible(true);
        });
    }
}